﻿import { ref, unref } from 'vue'
import { useMessage } from '/@/hooks/web/useMessage';
import { useScanStore } from '/@/store/modules/scan'
const { createMessage } = useMessage();
const scanStore = useScanStore()
const wsUrl = 'ws://127.0.0.1:9866';
export let socket_scan = null;
var lockReconnect = false; //避免心跳重复连接
var upload_filename = [];
const jsonPing = {
	type: 'CMD_ORDER',
	cmd: 'Ping',
};

// 实例化
createWebSocket(get_appropriate_ws_url());


//心跳重连
var heartCheck = {
	timeout: 60000, //1分钟发一次心跳
	timeoutObj: null,
	serverTimeoutObj: null,
	reset: function () {
		clearTimeout(this.timeoutObj);
		clearTimeout(this.serverTimeoutObj);
		return this;
	},
	start: function () {
		var self = this;
		this.timeoutObj = setTimeout(function () {
			//这里发送一个心跳，后端收到后，返回一个心跳消息，
			//onmessage拿到返回的心跳就说明连接正常
			socket_scan.send(JSON.stringify(jsonPing));
			console.log('ping!');
			self.serverTimeoutObj = setTimeout(function () {
				//如果超过一定时间还没重置，说明后端主动断开了
				socket_scan.close(); //如果onclose会执行reconnect，我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
			}, self.timeout);
		}, this.timeout);
	},
};

// 获取连接地址
function get_appropriate_ws_url() {
	var pcol;
	var u = document.URL;
	var ul = window.location.host;
	/*
	 * We open the websocket encrypted if this page came on an
	 * https:// url itself, otherwise unencrypted
	 */
	if (u.substring(0, 5) == 'https') {
		pcol = 'wss://localhost:';
	} else {
		//pcol = "ws://localhost:";
		pcol = 'ws://127.0.0.1:';
		//pcol = "wss://localhost:";
		//	pcol  = "ws://172.16.8.87:9000";
	}
	/* + "/xxx" bit is for IE10 workaround */
	pcol += '9866';
	return pcol;
}

function createWebSocket(url) {
	try {
		if (typeof MozWebSocket != 'undefined') {
			socket_scan = new MozWebSocket(get_appropriate_ws_url(), 'scanner-h5-protocol');
		} else {
			socket_scan = new WebSocket(get_appropriate_ws_url(), 'scanner-h5-protocol');
		}
		initEventHandle();
	} catch (e) {
		reconnect(url);
		console.log(e);
	}
}

const DS_List = ref(null)

function initEventHandle() {
	try {
		socket_scan.onopen = function () {
			heartCheck.reset().start();
			socket_scan.send(JSON.stringify(jsonPing));
		};
		var total = 0;
		var imgBase64 = '';
		socket_scan.onmessage = function got_packet(msg) {
			heartCheck.reset().start();
			var dat = msg.data;
			const jsonDat = JSON.parse(dat);

			if (jsonDat.type == 'STATUS') {
				if (jsonDat.data == 'not_ready') {
					return createMessage.warning('扫描机没有纸张')
				} else if (jsonDat.data == 'task_done') {
					//Post(upload_filename);
					var str = jsonDat.data + '页数' + jsonDat.num;
					console.log(str);
					console.log(upload_filename);
					var length = upload_filename.length;

					upload_filename.splice(0, upload_filename.length);
					//console.log(jsonDat.num);
				} else if (jsonDat.data == 'scan_error') {
					var str = jsonDat.data + '错误码' + jsonDat.error_code;
					console.log(str);
				} else if (jsonDat.data == 'upload_done') {
					var str = jsonDat.data + 'UPLOAD回传信息：' + jsonDat.response;
					console.log(str);
				} else if (jsonDat.data == 'upload_done_base64') {
					var str = jsonDat.data + '总共上传的图片张数：' + jsonDat.num;
					console.log(str);
				} else {
					console.log(jsonDat.data);
				}

				//console.log(jsonDat.error_code);
			} else if (jsonDat.type == 'FILE_NAME') {
				//Post(jsonDat.filename);
				upload_filename.push(jsonDat.filename);
				//Post(jsonDat.filename);
				total += jsonDat.base64.length;
				imgBase64 += jsonDat.base64;
				if (jsonDat.fragment == 'WRITE_FIN') {
					if (total == jsonDat.size) {
						console.log('收到文件 :' + jsonDat.filename + ' siez:' + total);
						var img = document.createElement('img');
						img.src = 'data:image/jpg;base64,' + imgBase64;
						img.width = 300;
						document.querySelector('.preview').appendChild(img);
						document.getElementById('disimg').src = 'data:image/jpg;base64,' + imgBase64;
					} else console.log('接收完毕,校验失败');
					total = 0;
					//console.log(imgBase64);
					imgBase64 = '';
				}
			} else if (jsonDat.type == 'DS_LIST') {
				//alert("jsonDat.type == DS_LIST");
				console.log(jsonDat.data, 'Ping');
				// DS_List.value = jsonDat.data
				scanStore.setEquipmentList(jsonDat.data)

			} else if (jsonDat.type == 'Ping') {
				console.log(jsonDat.data, 'Ping');

			}

		};

		socket_scan.onclose = function () {
			reconnect(get_appropriate_ws_url());

		};
	} catch (exception) {
		console.log('<p>Error' + exception);
	}

}

window.onbeforeunload = function () {
	socket_scan.close();
};


function reconnect(url) {
	if (lockReconnect) return;
	lockReconnect = true;
	setTimeout(function () {
		//没连接上会一直重连，设置延迟避免请求过多
		createWebSocket(url);
		lockReconnect = false;
	}, 2000);
}

// 获取设备列表
export const getDsList = () => {
	console.log(socket_scan);
	socket_scan.send(JSON.stringify({
		"type": "CMD_ORDER",
		"cmd": "get_ds_list"
	}));
}

/**
 * 
 * @param ds 设备名称
 */
export const scan = (ds) => {
	const scanner = {
		'type': 'SCAN_SETTING',
		'ds': "Uniscan Q350", //defualt ds,
		'scan_model': 1,
		'color_model': 2,
		'show_ui': 0,
		'dpi': 300,
		'file_format': 'pdf',
		'path_to_save': 'D:\\test\\',
		'file_name': 'f_',
		'index': 1,
		'encode_base64': 0,
		'rotation': 0
	};
	if (!import.meta.env.DEV) {
		scanner.path_to_save = 'C:\\test\\'
	}
	scanner.ds = ds; // 设备
	socket_scan.send(JSON.stringify(scanner));
}

export const post = (saved_file) => {
	//post 文件
	const jsonPost =
	{
		'type': 'CMD_ORDER',
		'cmd': 'POST',
		'file': 'D:\\test\\',
	}
	if (!import.meta.env.DEV) {
		jsonPost.file = 'C:\\test\\'
	}
	socket_scan.send(JSON.stringify(jsonPost));

}